package com.api.shopapi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.config.WebSocket;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.MeshDeviceDTO;
import com.api.shopapi.mapper.*;
import com.api.shopapi.service.AlarmRecordService;
import com.api.shopapi.service.DeviceYjsbjianService;
import com.api.shopapi.service.YJHeaderService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhaofujun.automapper.AutoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Console;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("YJHeaderServiceImplOne")
@Slf4j
public class YJHeaderServiceImpl implements YJHeaderService {


    @Autowired
    private YJHeaderMapper yjHeaderMapper;

    @Autowired
    private SBJHeartRateDataMapper sbjHeartRateDataMapper;

    @Autowired
    private SBJSleepAlarmMapper sbjSleepAlarmMapper;

    @Autowired
    private SBJSleepDurationMapper sbjSleepDurationMapper;

    @Autowired
    private SBJSleepReportMapper sbjSleepReportMapper;

    @Autowired
    private SBJStatusRecordMapper sbjStatusRecordMapper;

    @Autowired
    private MeshDeviceMapper meshDeviceMapper;

    @Autowired
    private MeshDevicePropertiesMapper meshDevicePropertiesMapper;

    @Autowired
    private MeshDeviceStatusPushMapper meshDeviceStatusPushMapper;



    @Autowired
    private DeviceYjgatewayMapper deviceYjgatewayMapper;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private AlarmRecordMapper alarmRecordMapper;

    @Autowired
    private DeviceYjsbjianMapper deviceYjsbjianMapper;

    @Value("${my.elderlyAlarm}")
    protected String pushAlarmPath;

    

    @Override
    @Transactional
    public int insert(YJHeader yjHeader, JSONObject payload) throws Exception{

        //mesh网关设备数据推送
        if (yjHeader.getName().equals("MeshDevPush")){
            JSONArray devices = payload.getJSONArray("devices");
            for (int i=0;i<devices.size();i++){
                JSONObject device = (JSONObject) devices.get(i);
                String deviceType = device.getString("deviceType");
                String zone = device.getString("zone");
                String deviceId = device.getString("deviceId");
                String deviceName = device.getString("deviceName");
                String brand = device.getString("brand");
                String model = device.getString("model");
                MeshDevice meshDevice=new MeshDevice();
                meshDevice.setDeviceCode(UUID.randomUUID().toString());
                meshDevice.setHeaderCode(yjHeader.getHeaderCode());
                meshDevice.setBrand(brand);
                meshDevice.setDeviceId(deviceId);
                meshDevice.setDeviceType(deviceType);
                meshDevice.setModel(model);
                meshDevice.setZone(zone);
                meshDevice.setDeviceName(deviceName);
                meshDevice.setAddTime(new Date());
                meshDeviceMapper.insert(meshDevice);

                String message="";
                String type="";
                int type1=0;
                List<MeshDeviceProperties> meshDevicePropertiesList=new ArrayList<>();
                JSONArray properties = device.getJSONArray("properties");
                for (int j=0;j<properties.size();j++){
                    JSONObject propertie = (JSONObject) properties.get(j);
                    String name = propertie.getString("name");
                    String updatetime = propertie.getString("updatetime");
                    String value = propertie.getString("value");
                    if (model.equals("SY25009")&&value.equals("clicked")){
                        message="检测到按钮被按下";
                        type="MESH智能养老网关";
                        type1=6;
                    }
                    if (model.equals("SY28016")&&value.equals("clicked")){
                        message="检测到按钮被按下";
                        type="MESH紧急按钮";
                        type1=2;
                    }
                    if (model.equals("SY28012")&&value.equals("pass")){
                        message="检测到有人经过";
                        type="MESH红外探测器";
                        type1=3;
                    }
                    if (model.equals("SY28013")&&value.equals("open")){
                        message="检测到门打开";
                        type="MESH门磁传感器";
                        type1=4;
                    }
                    if (model.equals("SY28013")&&value.equals("close")){
                        message="检测到门关闭";
                        type="MESH门磁传感器";
                        type1=4;
                    }
                    if (model.equals("SY28014")&&value.equals("water")){
                        message="检测到水，浸水报警";
                        type="MESH水浸传感器";
                        type1=5;
                    }
                    if (model.equals("SY28014")&&value.equals("anhydrous")){
                        message="未检测到水，浸水解除";
                        type="MESH水浸传感器";
                        type1=5;
                    }
                    if (model.equals("SY05039")&&value.equals("smoky")){
                        message="检测到烟雾";
                        type="MESH光电烟雾探测器";
                        type1=8;
                    }
                    if (model.equals("SY05040")&&value.equals("gas")){
                        message="检测到煤气";
                        type="MESH燃气泄漏报警器";
                        type1=9;
                    }

                    MeshDeviceProperties meshDeviceProperties=new MeshDeviceProperties();
                    meshDeviceProperties.setPropertiesCode(UUID.randomUUID().toString());
                    meshDeviceProperties.setName(name);
                    meshDeviceProperties.setValue(value);
                    meshDeviceProperties.setUpdateTime(timeStrToDate(updatetime));
                    meshDeviceProperties.setDeviceCode(meshDevice.getDeviceCode());
                    meshDevicePropertiesMapper.insert(meshDeviceProperties);
                    meshDevicePropertiesList.add(meshDeviceProperties);
                }

                User user=new User();
                DeviceYjgateway deviceYjgateway = deviceYjgatewayMapper.getByGatewayId(yjHeader.getGwId());
                if (deviceYjgateway!=null){
                    user = userMapper.getByUserCode(deviceYjgateway.getUserCode());
                }

                //插入信息到报警信息中
                AlarmRecord alarmRecord=new AlarmRecord();
                alarmRecord.setAlarmRecordCode(UUID.randomUUID().toString());
                alarmRecord.setCreateTime(new Date());
                alarmRecord.setDeviceName(deviceName);
                alarmRecord.setLocation(zone);
                alarmRecord.setUserCode(user.getUserCode());
                alarmRecord.setGovernmentCode(user.getGovernmentCode());
                alarmRecord.setType(type1);
                alarmRecord.setRemarks(message);
                alarmRecordMapper.insert(alarmRecord);

                //将信息推送给前端
                //将报警信息写入文件夹中
                ObjectMapper mapper=new ObjectMapper();
                MeshDeviceDTO meshDeviceDTO=new AutoMapper().map(meshDevice,MeshDeviceDTO.class);
                meshDeviceDTO.setDevicePropertiesList(meshDevicePropertiesList);
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("user",user);
                jsonObject.put("deviceId",deviceId);
                jsonObject.put("zone",zone);
                jsonObject.put("deviceType",type);
                jsonObject.put("message",message);
                jsonObject.put("deviceName",deviceName);
                jsonObject.put("model",model);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                jsonObject.put("sendTime",sdf.format(meshDevice.getAddTime()));

                String filePath=pushAlarmPath;
                String systemPath=pushAlarmPath+"/11111111-1111-1111-1111-111111111111";
                File file =new File(filePath);
                if  (!file .exists()  && !file .isDirectory())
                {
                    file .mkdir();
                }
                String governmentCode = user.getGovernmentCode();
                List<Staff> staffList = staffMapper.getByGovernmentCodeAndRoleCode(governmentCode, "df7f8940-0512-4e86-a8d4-ab8a8a330fbc");
                for (Staff staff : staffList) {
                    String fileNamePath=filePath+"/"+staff.getStaffCode();
                    File file1 =new File(fileNamePath);
                    if  (!file1 .exists()  && !file1 .isDirectory())
                    {
                        file1 .mkdir();
                    }
                    fileNamePath=fileNamePath+"/alarm"+new Date().getTime()+".txt";
                    mapper.writeValue(new File(fileNamePath),jsonObject);
                }


                //写到系统文件夹里
                File file2 =new File(systemPath);
                if  (!file2 .exists()  && !file2 .isDirectory())
                {
                    file2 .mkdir();
                }
                systemPath=systemPath+"/alarm"+new Date().getTime()+".txt";
                mapper.writeValue(new File(systemPath),jsonObject);
            }


            yjHeader.setAddTime(new Date());
            return yjHeaderMapper.insert(yjHeader);
        }



        //睡倍健数据推送
        if (yjHeader.getName().equals("HeartRateData")){//推送心率实时数据
            String deviceId = payload.getString("deviceId");
            int heartBeat = payload.getIntValue("heartBeat");
            int respiratoryRate = payload.getIntValue("respiratoryRate");
            int bodyMove = payload.getIntValue("bodyMove");
            int temperature = payload.getIntValue("temperature");
            String onBed = payload.getString("onBed");
            String sendDateTimeStr = payload.getString("sendDateTime");
            SBJHeartRateData heartRateData=new SBJHeartRateData();
            heartRateData.setHeartRateDataCode(UUID.randomUUID().toString());
            heartRateData.setBodyMove(bodyMove);
            heartRateData.setHeaderCode(yjHeader.getHeaderCode());
            heartRateData.setDeviceId(deviceId);
            heartRateData.setHeartBeat(heartBeat);
            heartRateData.setRespiratoryRate(respiratoryRate);
            heartRateData.setTemperature(temperature);
            heartRateData.setSendDateTime(timeStampStrToDate(sendDateTimeStr));
            heartRateData.setAddTime(new Date());
            if (onBed.equals("true")){
                heartRateData.setOnBed(1);
            }else {
                heartRateData.setOnBed(2);
            }
            sbjHeartRateDataMapper.insert(heartRateData);

            yjHeader.setAddTime(new Date());
            return yjHeaderMapper.insert(yjHeader);
        }

        if (yjHeader.getName().equals("SleepReport")){//睡眠报告
            String deviceId = payload.getString("deviceId");
            int sober = payload.getIntValue("sober");
            int lightSleep = payload.getIntValue("lightSleep");
            int deepSleep = payload.getIntValue("deepSleep");
            String startBedtime = payload.getString("startBedtime");
            String endBedtime = payload.getString("endBedtime");
            String sleepTime = payload.getString("sleepTime");
            int sleepHours = payload.getIntValue("sleepHours");
            int sleepQuality = payload.getIntValue("sleepQuality");
            int respiratoryRate = payload.getIntValue("respiratoryRate");
            int heartRate = payload.getIntValue("heartRate");
            int bodyMove = payload.getIntValue("bodyMove");
            int bedAway = payload.getIntValue("bedAway");
            int abnormal = payload.getIntValue("abnormal");
            String advice = payload.getString("advice");
            SBJSleepReport sleepReport=new SBJSleepReport();
            sleepReport.setSleepReportCode(UUID.randomUUID().toString());
            sleepReport.setHeaderCode(yjHeader.getHeaderCode());
            sleepReport.setAbnormal(abnormal);
            sleepReport.setAdvice(advice);
            sleepReport.setBedAway(bedAway);
            sleepReport.setDeepSleep(deepSleep);
            sleepReport.setLightSleep(lightSleep);
            sleepReport.setEndBedTime(timeStrToDate(endBedtime));
            sleepReport.setDeviceId(deviceId);
            sleepReport.setSober(sober);
            sleepReport.setStartBedTime(timeStrToDate(startBedtime));
            sleepReport.setSleepTime(timeStrToDate(sleepTime));
            sleepReport.setSleepHours(sleepHours);
            sleepReport.setSleepQuality(sleepQuality);
            sleepReport.setRespiratoryRate(respiratoryRate);
            sleepReport.setHeartRate(heartRate);
            sleepReport.setBodyMove(bodyMove);
            sleepReport.setAddTime(new Date());
            sbjSleepReportMapper.insert(sleepReport);
            JSONObject jsonObject = payload.getJSONObject("sleepDuration");
            Map<String, Object> sleepDurationMap = JSONObject.toJavaObject(jsonObject, Map.class);
            for (String key : sleepDurationMap.keySet()) {
                SBJSleepDuration sleepDuration=new SBJSleepDuration();
                sleepDuration.setSleepDurationCode(UUID.randomUUID().toString());
                sleepDuration.setSleepReportCode(sleepReport.getSleepReportCode());
                sleepDuration.setSendDateTime(timeStampStrToDate(key));
                sleepDuration.setSleepStatus(Integer.parseInt(sleepDurationMap.get(key)+""));
                sbjSleepDurationMapper.insert(sleepDuration);
            }

            yjHeader.setAddTime(new Date());
            return yjHeaderMapper.insert(yjHeader);
        }



        if(yjHeader.getName().equals("SleepAlarm")){// 睡眠报警
            //插入到睡眠报警表
            String deviceId = payload.getString("deviceId");
            String alarmType = payload.getString("alarmType");
            String sendDateTime = payload.getString("sendDateTime");
            SBJSleepAlarm sleepAlarm=new SBJSleepAlarm();
            sleepAlarm.setSleepAlarmCode(UUID.randomUUID().toString());
            sleepAlarm.setHeaderCode(yjHeader.getHeaderCode());
            sleepAlarm.setAlarmType(alarmType);
            sleepAlarm.setDeviceId(deviceId);
            sleepAlarm.setSendDateTime(timeStampStrToDate(sendDateTime));
            sleepAlarm.setAddTime(new Date());
            sbjSleepAlarmMapper.insert(sleepAlarm);

            //插入信息到报警信息表
            User user=new User();
            DeviceYjsbjian deviceYjsbjian = deviceYjsbjianMapper.getByDeviceId(deviceId);
            if (deviceYjsbjian!=null){
                user=userMapper.getByUserCode(deviceYjsbjian.getUserCode());
            }

            AlarmRecord alarmRecord=new AlarmRecord();
            alarmRecord.setAlarmRecordCode(UUID.randomUUID().toString());
            alarmRecord.setCreateTime(new Date());
            alarmRecord.setDeviceName("睡倍健");
            alarmRecord.setUserCode(user.getUserCode());
            alarmRecord.setGovernmentCode(user.getGovernmentCode());
            alarmRecord.setType(7);
            String remarks="";
            switch(alarmType){
                case "sleeplimitstart":
                    remarks="入睡过晚";
                    break;
                case "sleeplimitend":
                    remarks="起床过晚";
                    break;
                case "onbed":
                    remarks="上床时间过晚";
                    break;
                case "outbednumber":
                    remarks="离床次数多于设置值";
                    break;
                case "outbedtimeonce":
                    remarks="单次离床时间多于设置值";
                    break;
                case "outbedtimecount":
                    remarks="累计离床时间多于设置值";
                    break;
                case "bodymove":
                    remarks="体动次数多于设置值";
                    break;
                case "heartrate":
                    remarks="心率异常";
                    break;
                case "breath":
                    remarks="呼吸率异常";
                    break;
            }
            alarmRecord.setRemarks(remarks);
            alarmRecordMapper.insert(alarmRecord);

            yjHeader.setAddTime(new Date());
            return yjHeaderMapper.insert(yjHeader);
        }


        /* if (yjHeader.getName().equals("MeshDevAlivePush")){//mesh设备上线/离线推送

            String deviceType = payload.getString("deviceType");
            String zone = payload.getString("zone");
            String deviceId = payload.getString("deviceId");
            String deviceName = payload.getString("deviceName");
            String brand = payload.getString("brand");
            String model = payload.getString("model");
            String aliveStatus = payload.getString("aliveStatus");

            MeshDeviceStatusPush meshDeviceStatusPush=new MeshDeviceStatusPush();
            meshDeviceStatusPush.setMeshDeviceStatusCode(UUID.randomUUID().toString());
            meshDeviceStatusPush.setHeaderCode(yjHeader.getHeaderCode());
            meshDeviceStatusPush.setBrand(brand);
            meshDeviceStatusPush.setDeviceId(deviceId);
            meshDeviceStatusPush.setDeviceType(deviceType);
            meshDeviceStatusPush.setModel(model);
            meshDeviceStatusPush.setZone(zone);
            meshDeviceStatusPush.setDeviceName(deviceName);
            meshDeviceStatusPush.setAliveStatus(aliveStatus);
            meshDeviceStatusPush.setAddTime(new Date());
            meshDeviceStatusPushMapper.insert(meshDeviceStatusPush);

        }*/



         /*if(yjHeader.getName().equals("DevOfflinePush")){ //睡倍健设备离线推送
            String deviceId = payload.getString("deviceId");
            SBJStatusRecord sbjStatusRecord=new SBJStatusRecord();
            sbjStatusRecord.setSBJStatusRecordCode(UUID.randomUUID().toString());
            sbjStatusRecord.setHeaderCode(yjHeader.getHeaderCode());
            sbjStatusRecord.setDeviceId(deviceId);
            sbjStatusRecord.setMessage(deviceId+"设备离线了");
            sbjStatusRecord.setAddTime(new Date());
            sbjStatusRecordMapper.insert(sbjStatusRecord);
        }



        if(yjHeader.getName().equals("DevOnlinePush")){ //睡倍健设备在线推送
            String deviceId = payload.getString("deviceId");
            SBJStatusRecord sbjStatusRecord=new SBJStatusRecord();
            sbjStatusRecord.setSBJStatusRecordCode(UUID.randomUUID().toString());
            sbjStatusRecord.setHeaderCode(yjHeader.getHeaderCode());
            sbjStatusRecord.setDeviceId(deviceId);
            sbjStatusRecord.setMessage(deviceId+"设备上线了");
            sbjStatusRecord.setAddTime(new Date());
            sbjStatusRecordMapper.insert(sbjStatusRecord);
        }*/



         /* if (yjHeader.getName().equals("MeshDevHeartbeatPush")){//设备心跳推送
            JSONArray devices = payload.getJSONArray("devices");
            for (int i=0;i<devices.size();i++){
                JSONObject device = (JSONObject) devices.get(i);
                String deviceType = device.getString("deviceType");
                String zone = device.getString("zone");
                String deviceId = device.getString("deviceId");
                String deviceName = device.getString("deviceName");
                String brand = device.getString("brand");
                String model = device.getString("model");
                MeshDevice meshDevice=new MeshDevice();
                meshDevice.setDeviceCode(UUID.randomUUID().toString());
                meshDevice.setHeaderCode(yjHeader.getHeaderCode());
                meshDevice.setBrand(brand);
                meshDevice.setDeviceId(deviceId);
                meshDevice.setDeviceType(deviceType);
                meshDevice.setModel(model);
                meshDevice.setZone(zone);
                meshDevice.setDeviceName(deviceName);
                meshDevice.setAddTime(new Date());
                meshDeviceMapper.insert(meshDevice);
                JSONArray properties = device.getJSONArray("properties");
                for (int j=0;j<properties.size();j++){
                    JSONObject propertie = (JSONObject) properties.get(j);
                    String name = propertie.getString("name");
                    String updatetime = propertie.getString("updatetime");
                    String value = propertie.getString("value");
                    MeshDeviceProperties meshDeviceProperties=new MeshDeviceProperties();
                    meshDeviceProperties.setPropertiesCode(UUID.randomUUID().toString());
                    meshDeviceProperties.setName(name);
                    meshDeviceProperties.setValue(value);
                    meshDeviceProperties.setUpdateTime(timeStrToDate(updatetime));
                    meshDeviceProperties.setDeviceCode(meshDevice.getDeviceCode());
                    meshDevicePropertiesMapper.insert(meshDeviceProperties);
                }
            }
        }*/
       return 1;
    }



    //将字符串时间戳转换成date类型
    private static Date timeStampStrToDate(String timeStr) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(timeStr)));
        Date date = sdf.parse(sd);
        return date;
    }

    //将字符串时间转换成date类型
    private static Date timeStrToDate(String timeStr) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.parse(timeStr);
    }




}



